package container_cmds

import (
	"bufio"
	"fmt"
	"net/http"
	"os"
	"time"

	"github.com/docker/docker/api/types"
	"github.com/docker/docker/client"
	"github.com/spf13/cobra"
)

var startCmd = &cobra.Command{
	Use: "start",
	PreRunE: func(cmd *cobra.Command, args []string) error {
		if len(args) != 2 {
			return fmt.Errorf("need param [containerId] [serverPort]")
		}
		return nil
	},
	RunE: runStart,
}

func runStart(cmd *cobra.Command, args []string) error {
	containerId := args[0]
	serverPort := args[1]

	cli, err := client.NewClientWithOpts(client.FromEnv)
	if err != nil {
		return err
	}

	err = cli.ContainerStart(cmd.Context(), containerId, types.ContainerStartOptions{})
	if err != nil {
		return err
	}

	logReader, err := cli.ContainerLogs(cmd.Context(), containerId, types.ContainerLogsOptions{
		ShowStdout: true,
		ShowStderr: true,
		Follow:     true,
	})
	if err != nil {
		return err
	}
	defer logReader.Close()

	go func() {
		scanner := bufio.NewScanner(logReader)
		for scanner.Scan() {
			fmt.Println(scanner.Text())
		}
	}()

	go func() {
		for {
			time.Sleep(1 * time.Second)
			if checkServerPort(serverPort) {
				os.Exit(0)
			}
		}
	}()

	statReader, err := cli.ContainerStats(cmd.Context(), containerId, true)
	if err != nil {
		return err
	}
	defer statReader.Body.Close()
	scanner := bufio.NewScanner(logReader)
	for scanner.Scan() {
		//do nothing
	}

	return nil
}

func checkServerPort(serverPort string) bool {
	http.DefaultClient.Timeout = 1 * time.Second
	resp, err := http.DefaultClient.Get(fmt.Sprintf("http://127.0.0.1:%s/", serverPort))
	if err != nil {
		return false
	}
	defer resp.Body.Close()
	return true
}
